package kr.ac.hanyang.cs.park;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class PlayTask extends ListActivity {
	//private static final String MEDIA_PATH				= Environment.getExternalStorageDirectory() +"/_sesame/samples";		// using External Storage
	private static final String MEDIA_PATH				= "samples";			// using assets/samples
	private static final String ACCEPT_EXT				= ".wav";
	private ArrayList<String> sampleList				= new ArrayList<String>();
	private MediaPlayer oMP								= new MediaPlayer();
	private AssetFileDescriptor oAFD					= null;
	private HashMap<String, String> fnRef				= new HashMap<String, String>();
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// TODO Auto-generated method stub
		initFileNameReference();
		updateSampleList();
	}


	private void initFileNameReference() {
		// TODO: should update this filename reference map (fnRef) after adding/removing sample audio file(s) in assets/samples
		fnRef.put("gallery",	"갤러리");
		fnRef.put("calculator",	"계산기");
		fnRef.put("takepic",	"사진찍기");
		fnRef.put("internet",	"인터넷");
		fnRef.put("findmap",	"지도찾기");
		fnRef.put("kakaotalk",	"카카오톡");
		fnRef.put("playstore",	"플레이스토어");
	}
	
	private void updateSampleList() {
		/*
		File homeDir									= new File(MEDIA_PATH);

		if (!homeDir.isDirectory()) {
			homeDir.mkdirs();
		}

		if (homeDir.listFiles(new Mp3Filter()).length > 0) {
			for (File aSample : homeDir.listFiles(new Mp3Filter())) {
				sampleList.add(aSample.getName());
			}
			
			SampleListAdapter sampleListAdapter			= new SampleListAdapter(this, R.layout.optionitems, sampleList);
			setListAdapter(sampleListAdapter);
		}
		else {
			Toast.makeText(this, "실행 가능한 명령어가 존재하지 않습니다. 개발자에게 문의해주세요.", Toast.LENGTH_LONG).show();
		}
		*/
		String[] fileList;

		try {
			// get file list from assets/MEDIA_PATH 
			fileList									= this.getAssets().list(MEDIA_PATH);

			// check file has ACCEPT_EXT
			for (String file : fileList) {
				if(file.endsWith(ACCEPT_EXT)){
					sampleList.add(file);
				}
			}

			// add listener
			if (sampleList.size() > 0) {
				SampleListAdapter sampleListAdapter		= new SampleListAdapter(this, R.layout.optionitems, sampleList);
				setListAdapter(sampleListAdapter);
			}
			else {
				Toast.makeText(this, "실행 가능한 명령어가 존재하지 않습니다. 개발자에게 문의해주세요.", Toast.LENGTH_LONG).show();
			}			
		}
		catch (Exception e) {
			Log.e("ERROR", e.toString());
		}

	}

	private String getFileName(String fileNameAndExtension) {
		String fileName										= fileNameAndExtension.substring(0, fileNameAndExtension.length() - ACCEPT_EXT.length());
		
		if (fnRef.containsKey(fileName))
			return fnRef.get(fileName);
		else
			return fileName;
	}

	private void playSample(int sampleIdx) {
		try {
			String realName									= sampleList.get(sampleIdx);

			Log.i("INFO", "Playing: "+ MEDIA_PATH +"/"+ realName);

			oAFD										= getAssets().openFd(MEDIA_PATH +"/"+ realName);

			oMP.reset();
			//oMP.setDataSource(MEDIA_PATH +"/"+ sampleList.get(sampleIdx));		// using External Storage
			oMP.setDataSource(oAFD.getFileDescriptor(), oAFD.getStartOffset(), oAFD.getLength());	// using assets/samples
			oMP.prepare();
			oMP.start();


			Toast.makeText(this, "'"+ getFileName(realName) +"'의 예제를 재생합니다.", Toast.LENGTH_SHORT).show();

			oMP.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {				
				@Override
				public void onCompletion(MediaPlayer oMP) {
					oMP.stop();
				}
			});
		}
		catch (Exception e) {
			Log.e("ERROR", e.toString());
		}
	}

	
	private class SampleListAdapter extends ArrayAdapter<String> {
		private ArrayList<String> items;
//		private int selectedTaskNo						= -1;


		public SampleListAdapter(Context context, int textViewResourceId, ArrayList<String> items) {
			super(context, textViewResourceId, items);
			this.items									= items;
		}


		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v										= convertView;

			if (v == null) {
				LayoutInflater vi						= (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v										= vi.inflate(R.layout.mainitems, null);
			}


			String sampleName							= items.get(position);

			if (sampleName != null) {
				ImageView icon							= (ImageView)v.findViewById(R.id.main_imgIcon);
				TextView name							= (TextView) v.findViewById(R.id.main_txtTaskName);
				TextView desc							= (TextView) v.findViewById(R.id.main_txtDescription);

				// set default icon
				if (icon != null)
					icon.setImageDrawable(getResources().getDrawable(android.R.drawable.ic_btn_speak_now));

				if (name != null)
					name.setText(getFileName(sampleName));

				if (desc != null)
					desc.setText("'"+ getFileName(sampleName) +"'의 예제를 재생합니다.");

				// 현재 item의 position을 버튼에 tagging한 후, 클릭 시 이벤트 리스터에 넘김
				v.setTag(position);
				v.setOnClickListener(itemClickListener);
//				v.setOnLongClickListener(itemLongClickListener);
			}

			return v;
		}


		// run
		private View.OnClickListener itemClickListener = new View.OnClickListener() {
			public void onClick(View v) {
				playSample((Integer)v.getTag());
			}
		};

	}

	
	class Mp3Filter implements FilenameFilter {
		public boolean accept(File dir, String name) {
			return (name.endsWith(ACCEPT_EXT));
		}
	}

}